package loader.persister;

import java.util.HashMap;

import loader.parser.adapter.SiteAdapter;

import org.dom4j.Element;

public class DealPersister extends Persister {

	private static final int SHOPMODE = 1;
	private static final int DEALMODE = 0;

	private HashMap<String, String> shop;
	private HashMap<String, String> deal;
	private int mode;
	private int dealCount = 0;
	private int shopCount = 0;

	public DealPersister() {
	}

	public DealPersister(SiteAdapter adapter) {
		this.adapter = adapter;
	}

	@Override
	public void detectNewObject(Element ele) {
		if (getAdapter().isNewDeal(ele.getName())) {
			// 是否存在没有shop的deal? 如果存在则取消注释以下代码
			// if (deal != null) {
			// deal.put("id", this.dealCount + "");
			// this.persist("deal", deal);
			// this.dealCount++;
			// }
			deal = new HashMap<String, String>();
			mode = DEALMODE;
		} else if (getAdapter().isNewShop(ele.getName())) {
			if (shop != null) {
				if (deal != null) {
					deal.put("id", this.dealCount + "");
					this.persist("deal", deal);
					this.dealCount++;
					deal = null;
				}
				shop.put("id", this.shopCount + "");
				shop.put("dealId", this.dealCount - 1 + "");
				this.persist("shop", shop);
				this.shopCount++;
			}
			shop = new HashMap<String, String>();
			mode = SHOPMODE;
		}
	}

	@Override
	public void addProperty(Element ele) {
		String propertyName = getAdapter().getProperName(ele.getName());
		if (propertyName == null)
			return;
		if (mode == SHOPMODE)
			shop.put(propertyName, ele.getStringValue().trim());
		else if (mode == DEALMODE)
			deal.put(propertyName, ele.getStringValue().trim());
	}

	@Override
	public void clear() {
		this.clear("deal");
		this.dealCount = 0;
		this.clear("shop");
		this.shopCount = 0;
	}
}
